{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "正常情况下，当我们定义了一个class，创建了一个class的实例后，我们可以给该实例绑定任何属性和方法，这就是动态语言的灵活性。先定义class："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，尝试给实例绑定一个属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Michael\n"
     ]
    }
   ],
   "source": [
    "s = Student()\n",
    "s.name = 'Michael' # 动态给实例绑定一个属性\n",
    "print(s.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "还可以尝试给实例绑定一个方法：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "25"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def set_age(self, age): # 定义一个函数作为实例方法\n",
    "    self.age = age\n",
    "    \n",
    "from types import MethodType\n",
    "s.set_age = MethodType(set_age, s) # 给实例绑定一个方法\n",
    "s.set_age(25) # 调用实例方法\n",
    "s.age # 测试结果"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但是，给一个实例绑定的方法，对另一个实例是不起作用的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'Student' object has no attribute 'set_age'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-4-b60b92948bdf>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0ms2\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mStudent\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;31m# 创建新的实例\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ms2\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_age\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m25\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# 尝试调用方法\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'Student' object has no attribute 'set_age'"
     ]
    }
   ],
   "source": [
    "s2 = Student()# 创建新的实例\n",
    "s2.set_age(25) # 尝试调用方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了给所有实例都绑定方法，可以给class绑定方法：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def set_score(self, score):\n",
    "     self.score = score\n",
    "Student.set_score = set_score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "给class绑定方法后，所有实例均可调用："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s.set_score(100)\n",
    "s.score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s2.set_score(99)\n",
    "s2.score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通常情况下，上面的set_score方法可以直接定义在class中，但动态绑定允许我们在程序运行的过程中动态给class加上功能，这在静态语言中很难实现。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用__slots__\n",
    "但是，如果我们想要限制实例的属性怎么办？比如，只允许对Student实例添加name和age属性。\n",
    "\n",
    "为了达到限制的目的，Python允许在定义class的时候，定义一个特殊的 __ slots __ 变量，来限制该class实例能添加的属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 案例:\n",
    "s = Student() # 创建新的实例\n",
    "s.name = 'Michael' # 绑定属性'name'\n",
    "s.age = 25 # 绑定属性'age'\n",
    "s.score = 99 # 绑定属性'score'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于'score'没有被放到 __ slots __ 中，所以不能绑定score属性，试图绑定score将得到AttributeError的错误。\n",
    "\n",
    "使用 __ slots __ 要注意，__ slots __ 定义的属性仅对当前类实例起作用，对继承的子类是不起作用的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class GraduateStudent(Student):\n",
    "    pass\n",
    "\n",
    "g = GraduateStudent()\n",
    "g.score = 9999"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "除非在子类中也定义 __ slots __ ，这样，子类实例允许定义的属性就是自身的 __ slots __ 加上父类的 __ slots __ 。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用@property\n",
    "在绑定属性时，如果我们直接把属性暴露出去，虽然写起来很简单，但是，没办法检查参数，导致可以把成绩随便改：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = Student()\n",
    "s.score = 9999"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这显然不合逻辑。为了限制score的范围，可以通过一个set_score()方法来设置成绩，再通过一个get_score()来获取成绩，这样，在set_score()方法里，就可以检查参数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "\n",
    "    def get_score(self):\n",
    "         return self._score\n",
    "\n",
    "    def set_score(self, value):\n",
    "        if not isinstance(value, int):\n",
    "            raise ValueError('score must be an integer!')\n",
    "        if value < 0 or value > 100:\n",
    "            raise ValueError('score must between 0 ~ 100!')\n",
    "        self._score = value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，对任意的Student实例进行操作，就不能随心所欲地设置score了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "60"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = Student()\n",
    "s.set_score(60) # ok!\n",
    "s.get_score()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "score must between 0 ~ 100!",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-7-2900029cad0f>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mset_score\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m9999\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m<ipython-input-5-ee6f51991b93>\u001b[0m in \u001b[0;36mset_score\u001b[1;34m(self, value)\u001b[0m\n\u001b[0;32m      8\u001b[0m             \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'score must be an integer!'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      9\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mvalue\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m0\u001b[0m \u001b[1;32mor\u001b[0m \u001b[0mvalue\u001b[0m \u001b[1;33m>\u001b[0m \u001b[1;36m100\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 10\u001b[1;33m             \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'score must between 0 ~ 100!'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     11\u001b[0m         \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_score\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mValueError\u001b[0m: score must between 0 ~ 100!"
     ]
    }
   ],
   "source": [
    "s.set_score(9999)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但是，上面的调用方法又略显复杂，没有直接用属性这么直接简单。\n",
    "\n",
    "有没有既能检查参数，又可以用类似属性这样简单的方式来访问类的变量呢？对于追求完美的Python程序员来说，这是必须要做到的！\n",
    "\n",
    "还记得装饰器（decorator）可以给函数动态加上功能吗？对于类的方法，装饰器一样起作用。__Python内置的@property装饰器就是负责把一个方法变成属性调用的__："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "\n",
    "    @property\n",
    "    def score(self):\n",
    "        return self._score\n",
    "\n",
    "    @score.setter\n",
    "    def score(self, value):\n",
    "        if not isinstance(value, int):\n",
    "            raise ValueError('score must be an integer!')\n",
    "        if value < 0 or value > 100:\n",
    "            raise ValueError('score must between 0 ~ 100!')\n",
    "        self._score = value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "@property的实现比较复杂，我们先考察如何使用。把一个getter方法变成属性，只需要加上@property就可以了，此时，@property本身又创建了另一个装饰器@score.setter，负责把一个setter方法变成属性赋值，于是，我们就拥有一个可控的属性操作："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "60"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = Student()\n",
    "s.score = 60 # OK，实际转化为s.set_score(60)\n",
    "s.score # OK，实际转化为s.get_score()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "score must between 0 ~ 100!",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-10-4b335eedffe7>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mscore\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m9999\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32m<ipython-input-8-57f562f34ace>\u001b[0m in \u001b[0;36mscore\u001b[1;34m(self, value)\u001b[0m\n\u001b[0;32m     10\u001b[0m             \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'score must be an integer!'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     11\u001b[0m         \u001b[1;32mif\u001b[0m \u001b[0mvalue\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m0\u001b[0m \u001b[1;32mor\u001b[0m \u001b[0mvalue\u001b[0m \u001b[1;33m>\u001b[0m \u001b[1;36m100\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 12\u001b[1;33m             \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'score must between 0 ~ 100!'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     13\u001b[0m         \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_score\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mValueError\u001b[0m: score must between 0 ~ 100!"
     ]
    }
   ],
   "source": [
    "s.score = 9999"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意到这个神奇的@property，我们在对实例属性操作的时候，就知道该属性很可能不是直接暴露的，而是通过getter和setter方法来实现的。\n",
    "\n",
    "还可以定义只读属性，只定义getter方法，不定义setter方法就是一个只读属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student(object):\n",
    "\n",
    "    @property\n",
    "    def birth(self):\n",
    "        return self._birth\n",
    "\n",
    "    @birth.setter\n",
    "    def birth(self, value):\n",
    "        self._birth = value\n",
    "\n",
    "    @property\n",
    "    def age(self):\n",
    "        return 2020 - self._birth"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的birth是可读写属性，而age就是一个只读属性，因为age可以根据birth和当前时间计算出来。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 小结\n",
    "@property广泛应用在类的定义中，可以让调用者写出简短的代码，同时保证对参数进行必要的检查，这样，程序运行时就减少了出错的可能性。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 练习\n",
    "请利用@property给一个Screen对象加上width和height属性，以及一个只读属性resolution："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "resolution = 786432\n",
      "测试通过!\n"
     ]
    }
   ],
   "source": [
    "class Screen(object):\n",
    "    \n",
    "    @property\n",
    "    def width(self):\n",
    "        return self._width\n",
    "    \n",
    "    @width.setter\n",
    "    def width(self, value):\n",
    "        self._width = value\n",
    "        \n",
    "    @property\n",
    "    def height(self):\n",
    "        return self._height\n",
    "    \n",
    "    @height.setter\n",
    "    def height(self, value):\n",
    "        self._height = value\n",
    "        \n",
    "    @property\n",
    "    def resolution(self):\n",
    "        return self._width * self._height\n",
    "    \n",
    "# 测试:\n",
    "s = Screen()\n",
    "s.width = 1024\n",
    "s.height = 768\n",
    "print('resolution =', s.resolution)\n",
    "if s.resolution == 786432:\n",
    "    print('测试通过!')\n",
    "else:\n",
    "    print('测试失败!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
